<template>
  <div>
    <Upload
      v-model:fileList="fileList"
      name="file"
      list-type="picture-card"
      :customRequest="handlePreview"
      :showUploadList="{
        showPreviewIcon: props.showPreviewIcon,
        showRemoveIcon: props.showRemoveIcon,
        showDownloadIcon: props.showDownloadIcon,
      }"
      @preview="handlePreviewImg"
      @download="downLoadFile"
      @change="handleChange"
      @remove="handleRemove"
    >
      <div v-if="props.showUpload">
        <plus-outlined />
        <div style="margin-top: 8px">上传</div>
      </div>
    </Upload>
    <ImagePreview :imageList="[previewImage]" />
  </div>
</template>
<script lang="ts" setup>
  import { ref, defineProps, defineOptions, defineEmits, watch, onMounted } from 'vue';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { message, Upload } from 'ant-design-vue';
  import type { UploadChangeParam, UploadFile } from 'ant-design-vue';
  import { UploadRequestOption } from 'ant-design-vue/lib/vc-upload/interface';
  import { createImgPreview, ImagePreview } from '@/components/Preview';

  import { uploadApi, delFileApi, downloadFileApi } from '@/api/escloud/upload';

  import { downloadFile } from '@/utils/common';

  // import { v4 as uuidv4 } from 'uuid';

  defineOptions({ name: 'BasicUploadDragger' });

  const previewImage = ref<string>('');

  const props = defineProps({
    params: { type: [Object] },
    fileLists: { type: Array, default: () => [] },
    propUploadApi: { type: Function },
    showPreviewIcon: { type: Boolean, default: true },
    showRemoveIcon: { type: Boolean, default: true },
    showDownloadIcon: { type: Boolean, default: true },
    showUpload: { type: Boolean, default: true },
  });
  const emit = defineEmits(['uploadResult', 'handleChange']);
  const fileList = ref<any>([]);

  onMounted(() => {
    fileList.value = props.fileLists.map((item: any) => {
      return {
        ...item,
        name: item.fileOriginName || item.name,
        status: 'done',
        url: item.fileUrl || item.url,
      };
    });
  });

  watch(
    () => props.fileLists,
    (newVal, oldVal) => {
      if (newVal !== oldVal) {
        fileList.value = props.fileLists.map((item: any) => {
          return {
            ...item,
            name: item.fileOriginName || item.name,
            status: 'done',
            url: item.fileUrl || item.url,
          };
        });
      }
    },
    { deep: true }, // 如果 fileLists 是一个深层嵌套的对象数组，可能需要开启深度监听
  );

  // 下载文件
  const downLoadFile = async (file) => {
    try {
      const data = (await downloadFileApi(file.fileUrl)) as any;
      if (data) {
        downloadFile(data, file.name);
      } else {
        message.error('下载失败');
        return false;
      }
    } catch (error) {
      return false;
    }
  };

  const handlePreviewImg = async (file: UploadFile) => {
    const onImgLoad = ({ index, url, dom }) => {
      console.log(`第${index + 1}张图片已加载，URL为：${url}`, dom);
    };
    // 可以使用createImgPreview返回的 PreviewActions 来控制预览逻辑，实现类似幻灯片、自动旋转之类的骚操作
    console.log('file', file);

    console.log('previewImagexxxxxxxxxxxxxxxxxxxxxx', fileList);
    let urlList = fileList.value.map((item) => {
      return item.url ? item.url : item.response.fileUrl;
    });
    createImgPreview({
      imageList: urlList,
      defaultWidth: 700,
      rememberState: true,
      onImgLoad,
    });
  };

  const handleChange = (info: UploadChangeParam) => {
    console.log('🚀 ~ handleChange ~ info:', info);
    const status = info.file.status;

    if (status === 'done') {
      fileList.value = fileList.value.map((item) => {
        return {
          ...item,
          ...item.response,
        };
      });
      emit('handleChange', fileList.value);
    } else if (status === 'error') {
      fileList.value = fileList.value
        .map((item) => {
          if (item.uid === info.file.uid) {
            return null;
          } else {
            return item;
          }
        })
        .filter((ele) => {
          return ele;
        });
      message.error(`${info.file.name} 上传失败`);
    } else if (status === 'removed') {
      emit('handleChange', fileList.value);
    }
  };

  const handlePreview = async (info: UploadRequestOption<any>) => {
    const { onSuccess, onError, file } = info;
    const form = new FormData();
    // const batchId = uuidv4().split('-').join('');
    console.log('🚀 ~ handlePreview ~ props.params:', props.params);
    for (let key in props.params) {
      form.append(key, props.params[key]);
    }
    form.append('file', file);
    // form.append('batchId', batchId);
    const upload = props.propUploadApi ? props.propUploadApi : uploadApi;

    try {
      const res = await upload(form);
      console.log('上传结果', res);
      if (res) {
        emit('uploadResult', res);
        message.success('上传成功');

        onSuccess &&
          onSuccess({
            ...res,
          });
      } else {
        message.error('上传失败');
        onError && onError(res);
      }
    } catch (error) {
      onError && onError(error);
    }
  };

  const handleRemove = async (file: any): Promise<void | boolean> => {
    try {
      const res = await delFileApi(file.id);
      res && message.success('删除成功');
      return !!res;
    } catch (error) {
      return false;
    }
  };
</script>
